﻿namespace Sidvall.Security
{
	public class PrincipalContextManager
	{
		#region Public Members

		public Sidvall.Security.IPrincipalContextProvider PrincipalContextProvider { get; set; }

		#region GetSessionValue

		public object GetSessionValue(string key)
		{
			object value;

			if (string.IsNullOrWhiteSpace(key))
				return null;
			if (this.PrincipalContextProvider == null)
				return null;
			if (this.PrincipalContextProvider.SessionContext == null)
				return null;
			if (this.PrincipalContextProvider.SessionContext.TryGetValue(key, out value))
				return value;
			return null;
		}
		public T GetSessionValue<T>(string key)
		{
			return GetSessionValue(key, default(T));
		}
		public T GetSessionValue<T>(string key, T defaultValue)
		{
			object value;

			value = GetSessionValue(key);
			if (value == null)
				return defaultValue;
			return (T)value;
		}

		#endregion
		#region HasSessionValue

		public bool HasSessionValue(string key)
		{
			if (string.IsNullOrWhiteSpace(key))
				return false;
			if (this.PrincipalContextProvider == null)
				return false;
			if (this.PrincipalContextProvider.SessionContext == null)
				return false;
			return this.PrincipalContextProvider.SessionContext.ContainsKey(key);
		}

		#endregion
		#region RemoveSessionValue

		public void RemoveSessionValue(string key)
		{
			if (string.IsNullOrWhiteSpace(key))
				return;
			if (this.PrincipalContextProvider == null)
				return;
			if (this.PrincipalContextProvider.SessionContext == null)
				return;
			this.PrincipalContextProvider.SessionContext.Remove(key);
		}

		#endregion
		#region SetSessionValue

		public void SetSessionValue(string key, object value)
		{
			if (string.IsNullOrWhiteSpace(key))
				return;
			if (this.PrincipalContextProvider == null)
				return;
			if (this.PrincipalContextProvider.SessionContext == null)
				return;
			this.PrincipalContextProvider.SessionContext[key] = value;
		}

		#endregion

		#region ToString

		public override string ToString()
		{
			return "PrincipalContextManager - Sidvall.Security.IPrincipalContextProvider";
		}

		#endregion

		#endregion
		#region Constructors

		public PrincipalContextManager(Sidvall.Security.IPrincipalContextProvider principalContextProvider)
		{
			this.PrincipalContextProvider = principalContextProvider;
		}

		#endregion
	}
}
